﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataLib.Accounts.Bus;
using System.Data;
using DataLib.Common;

namespace Ewts.Storage
{
    public partial class CJONonlocalApply : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ListItem item = new ListItem();
                item.Text = "--请选择--";
                item.Value = "";
                DataLib.BLL.City bllCity = new DataLib.BLL.City();


                // 处理地
                dropGraphic.DataSource = bllCity.GetList("flag1='02'");
                dropGraphic.DataTextField = "cityname";
                dropGraphic.DataValueField = "cityname";
                dropGraphic.DataBind();
                dropGraphic.Items.Insert(0, item);

                //业务员
                if (Session["UserInfo"] == null)
                {
                    Response.Redirect("/accounts/login.aspx");
                }
                else
                {
                    User curUser = new User();
                    curUser = (User)Session["UserInfo"];

                    hidOperman.Value = curUser.UserName;
                    if (Request["cjoid"] != null && Request["cjoid"].ToString().Trim() != "")
                    {
                        hidCJOID.Value = Request["cjoid"].ToString().Trim();
                        bindShow(int.Parse(hidCJOID.Value));
                    }
                    else
                    {

                        string Add = "";
                        //string cumid = "";
                        string loadid = "";
                        DataLib.Model.CumtomerAddress addModel = new DataLib.Model.CumtomerAddress();
                        DataLib.Model.LoadNum loadModel = new DataLib.Model.LoadNum();
                        if (Request["RelationID"] != null && Request["RelationID"].Trim() != "")
                        {
                            Add = Request["RelationID"];
                            DataLib.Model.ProjectsRelation prmodel = new DataLib.BLL.ProjectsRelation().GetModel(int.Parse(Add));
                            this.hidRelid.Value = Add;

                            addModel = new DataLib.BLL.CumtomerAddress().GetModel((int)prmodel.AddressID);
                        }
                        if (Request["LoadID"] != null && Request["LoadID"].Trim() != ""&&Request["LoadID"].Trim() != "0")
                        {
                            loadid = Request["LoadID"];
                            loadModel = new DataLib.BLL.LoadNum().GetModel(int.Parse(loadid));
                            txtLoadNum.Text = loadModel.loadnum;
                            hidLoadID.Value = loadid;
                        }

                        BindbyRelid(int.Parse(Request["RelationID"].ToString()));
                        //txtLoadNum.Text = Code.NumGeneration.GetSerialNum("86", "LoadNum");
                        //txtCJO.Text = Code.NumGeneration.GetSerialNum(txtLoadNum.Text, "CJO");
                        txtNoticeDate.Text = DateTime.Now.ToString();

                        //hidCustomerAddID.Value = Add;
                        hidCustomerID.Value = addModel.customerid.ToString();

                    }
                }
            }
        }


        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string strErr = "";
            //if (!PageValidate.IsNumber(txtLoadNum.Text))
            //{
            //    strErr += "请勿自行修改LoadNum！\\n";
            //}
            //if (!PageValidate.IsNumber(txtCJO.Text))
            //{
            //    strErr += "请勿自行修改CJO！\\n";
            //}
            if (txtSaleman.Text.Trim().Length == 0)
            {
                strErr += "业务员姓名就为自动生成，请勿修改！\\n";
            }
            if (!PageValidate.IsDateTime(txtNoticeDate.Text))
            {
                strErr += "通知日期必须输入且必须为日期格式数据！\\n";
            }
            if (!PageValidate.IsDateTime(txtCollectDate.Text))
            {
                strErr += "收货日期必须输入且必须为日期格式数据！\\n";
            }
            if (!PageValidate.IsDateTime(txtCollectTime.Text))
            {
                strErr += "收货时间必须为时间格式数据！\\n";
            }
            if (txtCompany.Text.Trim().Length == 0)
            {
                strErr += "客户名称不能为空！\\n";
            }
            if (txtAddress.Text.Trim().Length == 0)
            {
                strErr += "收货地址不能为空！\\n";
            }
            if (hidbussinesstype.Value == "")
            {
                strErr += "请选择业务类型!\\n";
            }
            if (txtContactPerson.Text.Trim().Length == 0)
            {
                strErr += "客户联系人不能为空！\\n";
            }
            if (dropGraphic.SelectedValue == "")
            {
                strErr += "必须选择处理地！\\n";
            }
            //if (!PageValidate.IsNumber(txtContactPhoneNo.Text))
            //{
            //    strErr += "客户联系方式不能为空且必须为数字！\\n";
            //}
           if (strErr != "")
            {
                MessageBox.Show(this, strErr);
                return;
            }

            DataLib.Model.LoadNum lModel = new DataLib.Model.LoadNum();
            DataLib.Model.Cjo cModel = new DataLib.Model.Cjo();
            DataLib.Model.VehicleRequire vModel = new DataLib.Model.VehicleRequire();
            lModel = GetLoadModel();
            cModel = GetCjoModel((int)lModel.id, lModel.loadnum);
            vModel = GetVehModel();
            cModel.istyz = "无";
            cModel.belogcity = lModel.belongarea;
            cModel.graphiccity = lModel.Rubbisharea;
            cModel.loadnum = lModel.loadnum;

            DataLib.BLL.CJOItem bll = new DataLib.BLL.CJOItem();
            int loadid = bll.InsertCjoItem(lModel, cModel, vModel);
            try
            {
                if (loadid > 0)
                {
                    DataLib.Common.MessageBox.ShowAndRedirect(Page, "Load号：" + lModel.loadnum + "；CJO号：" + cModel.cjono, "/RDLC/CJONonlocalRDLC.aspx?cjoid=" + bll.GetCjoId(loadid).ToString());
                }

            }
            catch (Exception ex)
            {
                DataLib.Common.MessageBox.Show(this, ex.Message);
            }
        }

        #region 加载显示数据
        /// <summary>
        /// 根据项目地址ID绑定相关数据
        /// </summary>
        /// <param name="relfid">项目地址ID</param>
        protected void BindbyRelid(int relfid)
        {
            DataLib.Model.ProjectsRelation rmodel = new DataLib.BLL.ProjectsRelation().GetModel(relfid);
            DataLib.Model.Project pmodel = new DataLib.BLL.Project().GetModel((int)rmodel.ProjectID);

            DataLib.Model.ServerPoint spmodel = new DataLib.BLL.ServerPoint().GetModel((int)rmodel.ServerPointID);


            DataLib.Model.CumtomerAddress cumAddrModel = new DataLib.BLL.CumtomerAddress().GetModel((int)rmodel.AddressID);
            DataLib.Model.Cumtomer customerModel = new DataLib.BLL.Cumtomer().GetModel((int)pmodel.CustomerID);

            //txtCustomerCode.value = pmodel.CustomerNum;
            hidCustomerAddID.Value = rmodel.AddressID.ToString();
            txtCompany.Text = customerModel.companyname; ;
            txtContactPerson.Text = cumAddrModel.linkman;
            txtContactPhoneNo.Text = cumAddrModel.phone;
            txtAddress.Text = rmodel.AddresssName;

            //cjo显示业务员
            if (spmodel.Cjoperson_show != null && spmodel.Cjoperson_show != "" && (spmodel.Cjoperson_show.IndexOf('/') >= 1 || spmodel.Cjoperson_show.IndexOf('@') >= 1))
            {
                char[] carr = { '/', '@' };
                txtSaleman.ToolTip = spmodel.Cjoperson_show.Split(carr)[0];
                txtSaleman.Text = spmodel.Cjoperson_show.Split(carr)[1];
                User salman = new DataLib.Accounts.Bus.User(txtSaleman.ToolTip);
                txtPhoneNo.Text = salman.Phone;
            }

            txtLoadBelong.Value = pmodel.belongAddress;
        }
        #endregion


        #region 3个对象值

        /// <summary>
        /// 取得LoadNum值
        /// </summary>
        /// <returns></returns>
        public DataLib.Model.LoadNum GetLoadModel()
        {

            int cusAddrID = int.Parse(hidCustomerAddID.Value);
            DataLib.Model.CumtomerAddress addModel = new DataLib.BLL.CumtomerAddress().GetModel(cusAddrID);
            DataLib.Model.Cumtomer cumModel = new DataLib.BLL.Cumtomer().GetModel(addModel.customerid);
            DataLib.Model.LoadNum lModel = new DataLib.Model.LoadNum();
            if (hidLoadID.Value == "0" || hidLoadID.Value == null || hidLoadID.Value == "")
            {
                lModel.id = 0;
                lModel.addressid = cusAddrID;
                lModel.customerid = int.Parse(hidCustomerID.Value.Trim());
                lModel.finishWeight = 0;
                lModel.loadnum = Code.NumGeneration.GetSerialNum("86", "LoadNum");

                lModel.status = 1;
                lModel.totalWeight = 0;
            }
            else
            {
                lModel = new DataLib.BLL.LoadNum().GetModel(int.Parse(hidLoadID.Value));
            }
            lModel.belongarea = txtLoadBelong.Value;
            lModel.collectdate = DateTime.Parse(this.txtCollectDate.Text + " " + txtCollectTime.Text);
            lModel.goodsInfo = GetGoodsInfo();
            lModel.Rubbisharea = dropGraphic.SelectedValue;
            lModel.RubbishType = "";
            lModel.saleman = txtSaleman.ToolTip;
            return lModel;
        }
        /// <summary>
        /// 获取cjo对象
        /// </summary>
        /// <param name="loadNumID"></param>
        /// <returns></returns>
        public DataLib.Model.Cjo GetCjoModel(int loadNumID, string loadnum)
        {
            DataLib.Model.Cjo cModel = new DataLib.Model.Cjo();
            if (hidCJOID.Value.Trim() != "0" && hidCJOID.Value.Trim() != "")
            {
                cModel = new DataLib.BLL.Cjo().GetModel(int.Parse(hidCJOID.Value.Trim()));
            }
            else
            {
                cModel.id = 0;
                cModel.loadnumid = loadNumID;
                cModel.cjono = Code.NumGeneration.GetSerialNum(loadnum, "CJO");
                cModel.status = 2;
            }
            cModel.createtime = DateTime.Parse(txtNoticeDate.Text);
            cModel.islocal = false;

            User curUser = new User();
            //新增Cjo数据并得到其ID CJO状态改为待派车
            if (Session["UserInfo"] != null)
            {
                curUser = (User)Session["UserInfo"];
                cModel.operman = curUser.UserName;
            }

            //if (txtGoodsWeight.Text == null || txtGoodsWeight.Text == "")
            //{
            //    cModel.predictweight = 0;
            //}
            //else
            //    cModel.predictweight = decimal.Parse(txtGoodsWeight.Text);
            cModel.cjocolldate = DateTime.Parse(this.txtCollectDate.Text + " " + txtCollectTime.Text);
  //          cModel.addid = Convert.ToInt32(hidAddID.Value);
            cModel.goodsdesc = GetGoodsInfo();
            //cModel.rubbType = GetRubbishType();

            int relid = int.Parse(hidRelid.Value);
            int cusAddrID = (int)new DataLib.BLL.ProjectsRelation().GetModel(relid).AddressID;

            DataLib.Model.CumtomerAddress addModel = new DataLib.BLL.CumtomerAddress().GetModel(cusAddrID);
            DataLib.Model.Cumtomer cumModel = new DataLib.BLL.Cumtomer().GetModel(addModel.customerid);
            cModel.customerid = cumModel.id.ToString();
            cModel.customercode = cumModel.customercode;
            cModel.customername = cumModel.companyname;
            cModel.cjoadd = txtAddress.Text;
            cModel.cjolinkman = txtContactPerson.Text;
            cModel.cjophone = txtContactPhoneNo.Text;
            cModel.operman = hidOperman.Value;
            cModel.addid = relid;
            cModel.bussinesstype = hidbussinesstype.Value;
            return cModel;
        }

        /// <summary>
        /// 获取VehicleRequire对象
        /// </summary>
        /// <returns></returns>
        public DataLib.Model.VehicleRequire GetVehModel()
        {
            DataLib.Model.VehicleRequire vModel = new DataLib.Model.VehicleRequire();

            if (hidVID.Value.Trim() != "" && hidVID.Value.Trim() != "0")
            {
                vModel = new DataLib.BLL.VehicleRequire().GetModel(int.Parse(hidVID.Value.Trim()));
            }
            else
            {
                string payType = "";

                vModel.clearingform = payType;
                vModel.vehiclecount = 0; //暂时没用
            }

            vModel.other = txtVehiRequire.Text;//提货要求（工具，人）
             vModel.tools = GetToolsStr();

            return vModel;
        }

        public string GetGoodsInfo()
        {
            string str = "";
            str += txtgoods1.Text.Trim() + "@" + txtqty1.Text.Trim() + "|";
            str += txtgoods2.Text.Trim() + "@" + txtqty2.Text.Trim() + "|";
            str += txtgoods3.Text.Trim() + "@" + txtqty3.Text.Trim() + "|";
            str += txtgoods4.Text.Trim() + "@" + txtqty4.Text.Trim() + "|";
            str += txtgoods5.Text.Trim() + "@" + txtqty5.Text.Trim() + "|";
            str += txtgoods6.Text.Trim() + "@" + txtqty6.Text.Trim() + "|";
            str += txtgoods7.Text.Trim() + "@" + txtqty7.Text.Trim() + "|";
            str += txtgoods8.Text.Trim() + "@" + txtqty8.Text.Trim() + "|";
            str += txtgoods9.Text.Trim() + "@" + txtqty9.Text.Trim() + "|";
            str += txtgoods10.Text.Trim() + "@" + txtqty10.Text.Trim() + "|";
            str += txtgoods11.Text.Trim() + "@" + txtqty11.Text.Trim() + "|";
            str += txtgoods12.Text.Trim() + "@" + txtqty12.Text.Trim();
            return str;
        }

        #endregion

        #region 修改异地CJO
        /// <summary>
        /// 设置显示控件
        /// </summary>
        /// <param name="cjoid"></param>
        public void bindShow(int cjoid)
        {
            DataLib.Model.CJOItem model = new DataLib.Model.CJOItem();
            model = new DataLib.BLL.CJOItem().GetListByCid(cjoid);
            DataLib.Model.Cjo cjo = new DataLib.BLL.Cjo().GetModel(cjoid);

            #region 绑定load数据
            hidRelid.Value = model.prorelid.ToString();
            hidLoadID.Value = model.loadnumid.ToString();
            hidVID.Value = model.vehichlerequireid.ToString();
            txtLoadBelong.Value = model.belongArea;
            txtCollectDate.Text = ((DateTime)model.CjoColldate).ToShortDateString();
            txtCollectTime.Text = ((DateTime)model.CjoColldate).ToShortTimeString();
            txtLoadNum.Text = model.loadnumno;
            dropGraphic.SelectedValue = model.Graphicy;
            txtSaleman.ToolTip = model.cjoshowmanusername;
            txtSaleman.Text = model.cjoshowmantruename;
            User suser = new DataLib.Accounts.Bus.User(txtSaleman.ToolTip);
            txtPhoneNo.Text = suser.Phone;
            txtNoticeDate.Text = model.createtime.ToString();
            txtCompany.Text = model.companyname;
            hidCustomerAddID.Value = model.Addressid.ToString();
            #endregion

            #region 绑定CJO数据
            txtCJO.Text = model.cjono;
            txtAddress.Text = model.cjoaddinfo;
            txtContactPerson.Text = model.cjolinkman;
            txtContactPhoneNo.Text = model.cjophone;
            hidbussinesstype.Value = cjo.bussinesstype;
            if (cjo.bussinesstype != null && cjo.bussinesstype != "")
            {
                if (cjo.bussinesstype == "销毁")
                {
                    bussDest.Checked = true;
                }
                else
                {
                    bussUsed.Checked = true;
                }
            }
            //hidOperman.Value = model.operman;
            #endregion

            txtVehiRequire.Text = model.other;
            bindTools(model.tools);
            bindGoodsInfo(model.goodsdesc);

        }

        /// <summary>
        /// 绑定工具
        /// </summary>
        /// <param name="tools"></param>
        public void bindTools(string tools)
        { 
                   string[] toolsReqList = tools.Split(',');
                for (int index = 0; index < toolsReqList.Length; index += 2)
                {
                    if (rbTools1.Text == toolsReqList[index])
                    {
                        rbTools1.Checked = true;
                        
                        txtTools1.Text = toolsReqList[index + 1].Split(';')[0];
                    }
                    if (rbTools2.Text == toolsReqList[index])
                    {
                        rbTools2.Checked = true;
                        txtTools2.Text = toolsReqList[index + 1].Split(';')[0];
                    }
                    if (rbTools3.Text == toolsReqList[index])
                    {
                        rbTools3.Checked = true;
                        txtTools3.Text = toolsReqList[index + 1].Split(';')[0];
                    }
                    if (rbTools4.Text == toolsReqList[index])
                    {
                        rbTools4.Checked = true;
                        txtTools4.Text = toolsReqList[index + 1].Split(';')[0];
                    }
                    if (rbTools5.Text == toolsReqList[index])
                    {
                        rbTools5.Checked = true;
                        txtTools5.Text = toolsReqList[index + 1].Split(';')[0];
                    }
                    if (rbTools6.Text == toolsReqList[index])
                    {
                        rbTools6.Checked = true;
                        txtTools6.Text = toolsReqList[index + 1].Split(';')[0];
                    }
                } 
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="goodsinfo"></param>
        public void bindGoodsInfo(string goodsinfo)
        {
            if (goodsinfo != null && goodsinfo.Trim() != "")
            {
                char [] carr = {'@','|'};
                string [] strarr = goodsinfo.Split(carr);

                if (strarr.Length >= 24)
                {
                    txtgoods1.Text = strarr[0];
                    txtgoods2.Text = strarr[2];
                    txtgoods3.Text = strarr[4];
                    txtgoods4.Text = strarr[6];
                    txtgoods5.Text = strarr[8];
                    txtgoods6.Text = strarr[10];
                    txtgoods7.Text = strarr[12];
                    txtgoods8.Text = strarr[14];
                    txtgoods9.Text = strarr[16];
                    txtgoods10.Text = strarr[18];
                    txtgoods11.Text = strarr[20];
                    txtgoods12.Text = strarr[22];

                    txtqty1.Text = strarr[1];
                    txtqty2.Text = strarr[3];
                    txtqty3.Text = strarr[5];
                    txtqty4.Text = strarr[7];
                    txtqty5.Text = strarr[9];
                    txtqty6.Text = strarr[11];
                    txtqty7.Text = strarr[13];
                    txtqty8.Text = strarr[15];
                    txtqty9.Text = strarr[17];
                    txtqty10.Text = strarr[19];
                    txtqty11.Text = strarr[21];
                    txtqty12.Text = strarr[23];
                }
            }
            
        }
        #endregion


        /// <summary>
        /// 获取工具要求
        /// </summary>
        /// <returns></returns>
        private string GetToolsStr()
        {
            string toolsReq = "";
            if (rbTools1.Checked == true)
                toolsReq += rbTools1.Text + "," + txtTools1.Text + ";";
            if (rbTools2.Checked == true)
                toolsReq += rbTools2.Text + "," + txtTools2.Text + ";";
            if (rbTools3.Checked == true)
                toolsReq += rbTools3.Text + "," + txtTools3.Text + ";";
            if (rbTools4.Checked == true)
                toolsReq += rbTools4.Text + "," + txtTools4.Text + ";";
            if (rbTools5.Checked == true)
                toolsReq += rbTools5.Text + "," + txtTools5.Text + ";";
            if (rbTools6.Checked == true)
                toolsReq += rbTools6.Text + "," + txtTools6.Text + ";";
            return toolsReq;
        }

    }

  
}